<?php
if(isset($_POST['submit'])){
    $attachment = $_POST['attachment'];
    $renamed = $_POST['renamed'];
    
    echo '<pre>';
    print_r(json_decode($attachment));
    echo '</pre>';
    
    echo '<pre>';
    print_r(json_decode($renamed));
    echo '</pre>';
}


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>

<title>Plupload - Custom example</title>

<style type="text/css">
	body {
		font-family:Verdana, Geneva, sans-serif;
		font-size:13px;
		color:#333;
		background:url(bg.jpg);
	}
</style>

<script type="text/javascript" src="js/browserplus-min.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>

<script type="text/javascript" src="js/plupload.js"></script>
<script type="text/javascript" src="js/plupload.gears.js"></script>
<script type="text/javascript" src="js/plupload.silverlight.js"></script>
<script type="text/javascript" src="js/plupload.flash.js"></script>
<script type="text/javascript" src="js/plupload.browserplus.js"></script>
<script type="text/javascript" src="js/plupload.html4.js"></script>
<script type="text/javascript" src="js/plupload.html5.js"></script>

<script>
    var jq = jQuery.noConflict();
</script>

</head>
<body>

<h1>Custom example</h1>

<p>Shows you how to use the core plupload API.</p>
<form method="post" action="">
    <div id="container">
        <div id="filelist">No runtime found.</div>
        <br />
        <a id="pickfiles" href="javascript:;">[Select files]</a> 
        <a id="uploadfiles" href="javascript:;">[Upload files]</a>
        <table id="attachment">
            <thead>
                <th>STT</th>
                <th>Ten file</th>
                <th>Nguoi nhan</th>
                <th>Size</th>
                <th>Status</th>
                <th>Action</th>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    <div id="hidden">
        <textarea name='attachment' id='attachment_value'></textarea>
        <!--<input name='renamed' id='renamed_value'/>-->
    </div>
    <input type="submit" name="submit" value="ok"/>
</form>

<script type="text/javascript">
// Custom example logic
var uploader = new plupload.Uploader({
	runtimes : 'gears,html5,flash,silverlight,browserplus',
	browse_button : 'pickfiles',
	container: 'container',
    //unique_names : true,
	//max_file_size : '500mb',
	url : 'upload.php',
	//resize : {width : 320, height : 240, quality : 90},
	flash_swf_url : 'js/plupload.flash.swf',
	silverlight_xap_url : 'js/plupload.silverlight.xap',
	filters : [
        {title : "All file", extensions : "*"}, // lay tat ca extension
        //{title : "All file", extensions : "pdf,jpg,zip,png,jpeg,rar,docx,doc,xls,xlsx,exe,csv,txt"}, // lay tat ca extension
		//{title : "Zip files", extensions : "zip"} // extion mac dinh
	]
});

uploader.bind('Init', function(up, params) {
	jq('#filelist').innerHTML = "<div>Current runtime: " + params.runtime + "</div>";
});

uploader.init();

uploader.bind('FilesAdded', function(up, files) {
    var stt = 1;
	for (var i in files) {
        
		//jq('filelist').innerHTML += '<div id="' + files[i].id + '">' 
        //+ files[i].name + ' (' + plupload.formatSize(files[i].size) + ') <b></b></div>';

        var content_att =   '<tr id="' + files[i].id + '">';
        content_att +=  '<td>'+stt+'</td>';
        content_att +=  '<td>'+ files[i].name +'</td>';
        content_att +=  '<td id="re_' + files[i].name + '"></td>';
        content_att +=  '<td>'+ plupload.formatSize(files[i].size) +'</td>';
        content_att +=  '<td><b></b></td>';
        content_att +=  '<td id="act_'+files[i].id+'"></td>';
        //content_att +=  '<td id="hidden_'+files[i].id+'">'+'<input name="att[name][id]" value="'+files[i].id+'"/></td>'; // chua nhung input hidden                     
        content_att += '</tr>';
        jq('#attachment tbody').append(content_att);  
        
        stt++;
	}
     
});

uploader.bind('UploadProgress', function(up, file) {
	jq('#'+file.id).find('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
    //jq('#act_'+file.id).html('<a href="#" class="del" rel="'+file.id+'">Del</a>'); // custom
});

// luu lai ten file csv, tai sao khong luu o add file
// neu luu o add file thi ten file bi trung tu doi ten file,khong nhan dc ten file cuoi cung
var nameFileCSV = ''; // custome giu lai ten file csv

// array renamed
//var renamed = {};
uploader.bind('FileUploaded', function(up, file, info) {
    jq('#act_'+file.id).html('<a href="#" class="del" rel="'+file.id+'">DELETE</a>');
    
    var obj = JSON.parse(info.response);
    
    // save file renamed
    //renamed[file.name] = obj.fileName;
    //alert('#re_'+file.name);
   
    document.getElementById('re_'+file.name).setAttribute('class', obj.fileName);
    // xu ly lay file csv receition
    if(file.name.toLowerCase() == 'recipients.csv'){
        nameFileCSV = file.name;
    }
});

// xu ly doc file csv va insert nguoi nhan
uploader.bind('UploadComplete', function(up, file) {
    
    if(nameFileCSV){
        jq.post("ajaxReadCSV.php",{ name : nameFileCSV })
            .done(function(data){
                var list_re = JSON.parse(data);
                console.log(list_re);
                for(file in list_re){ // for file name 1.pdf
                    
                    // td file name, khong dung jquery vi ten file co dang 1.pdf, bi hieu lam voi class selector
                    var td_rec = document.getElementById('re_'+file); //jq('#re_'+file);
                    
                    //alert('re_'+file);
                    if(!td_rec){
                        continue;
                    }
                    // xoa recipient cu, nhap moi hoan toan
                    td_rec.innerHTML = '';
                    
                    for(recipient in list_re[file]){ // for recipient array(0=>'U_1001', 1=>'G_2')
                        var name_rec = list_re[file][recipient];
     
                        if(td_rec.innerHTML){ // 2 ng nhan tro len
                            td_rec.innerHTML += ','+name_rec;    
                        }else{ // 1 ng nhan duy nhat
                            td_rec.innerHTML = name_rec;
                        }
                        
                        // gan cac input hidden
                        
                        
                    }// end for recipient
                } // end for file name
                
                jq('#attachment_value').val(getRecipient()); // giu lai gia tri danhsach ng nhan json
                //jq('#renamed_value').val(JSON.stringify(renamed)); // danh sach cac ten file da duoc rename
                                
            }); // end done post ajax
    }// end if nameFileCSV
});

uploader.bind('Error',function(up, file) {
    jq('#act_'+file.id).html('<a href="#" class="reupload" rel="'+file.id+'">REUPLOAD</a>');
    alert(file.name);
});
/*uploader.bind('StateChanged', function(up) {
    //up.state == plupload.STARTED
    str = 'aaaa';
    switch(up.state){
        case plupload.STARTED:
            str = 'STARTED';
        break;
        case plupload.QUEUED:
            str = 'QUEUED';
        break;
        case plupload.UPLOADING:
            str = 'UPLOADING';
        break;
        case plupload.FAILED:
            str = 'FAILED';
        break;
        case plupload.DONE:
            str = 'DONE';
        break;
        
    }
    alert(str);
    jq('#status').append(str+'\n');
});*/

// lay danh sach ten file va nguoi nhan tuong ung
function getRecipient(){
    var data = {};
    jq('td[id^="re_"]').each(function(key){
        var value = jq(this).html();
        if(value){
            data[jq(this).attr('class')] = value;
        }
    });
    
    return JSON.stringify(data);
}

jq('#attachment tbody').on('click', '.del', function(){
    // xoa dong hien tai trong table
    jq(this).parent().parent().remove();
    
    //set lai danh sach attachment
    jq('#attachment_value').val(getRecipient());
    
    return false;
})

jq('#uploadfiles').click(function(){
    uploader.start();
});



</script>
</body>
</html>